package com.ruge.spring.cloud.gateway.filter;

import com.ruge.spring.cloud.gateway.base.exception.BaseBusinessException;
import com.ruge.spring.cloud.gateway.base.exception.SystemError;
import com.ruge.spring.cloud.gateway.base.response.Response;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 * @author 嘿丷如歌
 * @version V1.0
 * @Description:
 * @date 2021/4/26 21:56
 */
@Component
public class SendErrorExtFilter implements ErrorWebExceptionHandler, Ordered {


    @Override
    public int getOrder() {
        return 10;
    }

    @Override
    public Mono<Void> handle(ServerWebExchange serverWebExchange, Throwable throwable) {

        ServerHttpResponse response = serverWebExchange.getResponse();
        Response baseResponse = new Response();
        baseResponse.setStatus(Response.Status.FAILED);
        if (throwable instanceof BaseBusinessException) {
            // 业务错误
            BaseBusinessException ex = (BaseBusinessException) throwable;
            baseResponse.setErrorCode(ex.getError().getErrorCode());
            baseResponse.setErrorMessage(ex.getError().getErrorMessage());
            baseResponse.setExtMessage(ex.getExtMessage());
            response.setStatusCode(HttpStatus.OK);
        } else {
            // apigateway unknown error.
            baseResponse.setErrorCode(SystemError.SYSTEM_INTERNAL_ERROR.getErrorCode());
            baseResponse.setErrorMessage(SystemError.SYSTEM_INTERNAL_ERROR.getErrorMessage());
            baseResponse.setExtMessage("api-gateway unknown error.");
            response.setStatusCode(HttpStatus.BAD_GATEWAY);
        }
        return null;
    }
}
